package com.sc.service.impl.vehicle;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sc.domain.VehicleCar;
import com.sc.dto.VehicleCarRequest;
import com.sc.mapper.VehicleCarMapper;
import com.sc.service.vehicle.IVehicleCarService;
import com.sc.util.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
public class IVehicleCarServiceImpl extends ServiceImpl<VehicleCarMapper, VehicleCar>
        implements IVehicleCarService {

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private VehicleCarMapper vehicleCarMapper;

    @Override
    public Boolean addVehicleCar(VehicleCarRequest vehicleCarRequest) {
        try {
            // 处理车辆信息
            VehicleCar vehicleCar = vehicleCarRequest.getVehicleCar();
            // 获取并设置图片路径
        List<String> imageUrls = vehicleCarRequest.getImages();  // 获取图片路径的列表
        if (imageUrls != null && !imageUrls.isEmpty()) {
            // 将图片路径合并成逗号分隔的字符串存储到数据库
            vehicleCar.setImages(String.join(",", imageUrls));
        }
 // 插入车辆信息
       // 判断是新增还是修改
        if (vehicleCar.getId() != null) {
            // 检查是否存在对应记录
            VehicleCar existingVehicleCar = vehicleCarMapper.selectById(vehicleCar.getId());
            if (existingVehicleCar != null) {
                // 更新车辆信息
                vehicleCarMapper.updateById(vehicleCar);
            } else {
                // 如果 ID 不存在对应记录，则认为是新增
                vehicleCarMapper.insert(vehicleCar);
            }
        } else {
            // 如果 ID 为 null，则直接新增
            vehicleCarMapper.insert(vehicleCar);
        }
            return true;  // 返回保存结果
        } catch (Exception e) {
            e.printStackTrace();
            return false; // 保存失败
        }
    }

    @Override
    public Page<VehicleCar> showCars(String carNo, Integer pageNum, Integer pageSize) {
        Page<VehicleCar> page = Page.of(pageNum, pageSize);
        QueryWrapper<VehicleCar> wrapper = new QueryWrapper<>();
        if (carNo != null) {
            wrapper.like("car_no", carNo);
        }
        page(page, wrapper);
        return page;
    }

    @Override
public String uploadImage(MultipartFile file) {
    try {
        // 返回文件的 URL，通过 Nginx 反向代理来访问
        return aliOssUtil.uploadImage(file);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("文件上传失败", e);
    }
}
}
